﻿using System.Collections.ObjectModel;
using YY.Admin.Core;
using YY.Admin.Event;

namespace YY.Admin.Module
{
    /// <summary>
    /// 单个标签的数据模型
    /// </summary>
    public class TabItemModel : BindableBase
    {
        public ObservableCollection<TabItemModel>? OpenTabs { get; set; }

        public IEventAggregator? EventAggregator { get; set; }

        private string? _id;
        public string? Id
        {
            get => _id;
            set => SetProperty(ref _id, value);
        }

        private string? _header;
        public string? Header
        {
            get => _header;
            set => SetProperty(ref _header, value);
        }

        private string? _icon = string.Empty;
        public string? Icon
        {
            get => _icon;
            set => SetProperty(ref _icon, value);
        }

        private IconTypeEnum? _iconType;
        public IconTypeEnum IconType {
            get {
                return _iconType ?? IconTypeEnum.AntDesign;
            }
            set => SetProperty(ref _iconType, value);
        }

        private string? _viewName = string.Empty;
        public string? ViewName
        {
            get => _viewName;
            set => SetProperty(ref _viewName, value);
        }

        /// <summary>
        /// Tab是否允许关闭
        /// </summary>
        private bool _isClosable = true;
        public bool IsClosable
        {
            get => _isClosable;
            set => SetProperty(ref _isClosable, value);
        }

        private bool _isSelected;
        public bool IsSelected
        {
            get => _isSelected;
            set => SetProperty(ref _isSelected, value);
        }

        // 添加对Tab源的引用
        public TabSource? TabSource { get; set; }

        /// <summary>
        /// 左侧是否有可关闭Tab
        /// </summary>
        public bool HasClosableLeft => OpenTabs != null && OpenTabs
            .Take(OpenTabs.IndexOf(this))
            .Any(t => t.IsClosable);

        /// <summary>
        /// 右侧是否有可关闭Tab
        /// </summary>
        public bool HasClosableRight => OpenTabs != null && OpenTabs
            .Skip(OpenTabs.IndexOf(this) + 1)
            .Any(t => t.IsClosable);

        /// <summary>
        /// 其他Tab（除当前）是否有可关闭Tab
        /// </summary>
        public bool HasClosableOther => OpenTabs != null && OpenTabs
            .Where(t => t != this)
            .Any(t => t.IsClosable);

        /// <summary>
        /// 是否有任意可关闭Tab（全部）
        ///</summary>
        public bool HasClosableAny => OpenTabs != null && OpenTabs
            .Any(t => t.IsClosable);

        public DelegateCommand<TabItemModel> RefreshTabCommand { get; }
        public DelegateCommand<TabItemModel> CloseTabCommand { get; }
        public DelegateCommand<TabItemModel> CloseLeftTabsCommand { get; }
        public DelegateCommand<TabItemModel> CloseRightTabsCommand { get; }
        public DelegateCommand<TabItemModel> CloseOtherTabsCommand { get; }
        public DelegateCommand<TabItemModel> CloseAllTabsCommand { get; }

        public TabItemModel()
        {
            Id = $"TabRegion_{Guid.NewGuid():N}"; // 保证唯一

            RefreshTabCommand = new DelegateCommand<TabItemModel>(RefreshTab);
            CloseTabCommand = new DelegateCommand<TabItemModel>(CloseTab);
            CloseLeftTabsCommand = new DelegateCommand<TabItemModel>(CloseLeftTabs);
            CloseRightTabsCommand = new DelegateCommand<TabItemModel>(CloseRightTabs);
            CloseOtherTabsCommand = new DelegateCommand<TabItemModel>(CloseOtherTabs);
            CloseAllTabsCommand = new DelegateCommand<TabItemModel>(CloseAllTabs);
        }

        /// <summary>
        /// 刷新当前Tab
        /// </summary>
        /// <param name="tabItemModel"></param>
        private void RefreshTab(TabItemModel tabItemModel)
        {
            if (tabItemModel?.TabSource == null)
            {
                return;
            }
            // 发布事件
            EventAggregator?.GetEvent<TabRefreshEvent>().Publish(tabItemModel);
        }

        /// <summary>
        /// 关闭当前Tab
        /// </summary>
        /// <param name="tabItemModel"></param>
        private void CloseTab(TabItemModel tabItemModel)
        {
            if (tabItemModel?.IsClosable != true || OpenTabs?.Any() != true)
            {
                return;
            }
            // 发布事件
            EventAggregator?.GetEvent<TabClosedEvent>().Publish(tabItemModel);

            // 从集合中移除标签
            OpenTabs.Remove(tabItemModel);
        }

        /// <summary>
        /// 关闭左侧Tab
        /// </summary>
        private void CloseLeftTabs(TabItemModel tabItemModel)
        {
            if (OpenTabs?.Any() != true)
            {
                return;
            }

            // 找到当前 Tab 的索引
            int currentIndex = OpenTabs.IndexOf(tabItemModel);
             // 左侧没有 Tab
            if (currentIndex <= 0)
            {
                return;
            }

            // 找出左侧所有可关闭的 Tab
            var leftTabs = OpenTabs
                .Take(currentIndex)               // 取前面所有 Tab
                .Where(t => t.IsClosable)         // 只关闭可关闭的
                .ToList();                        // 先 ToList 避免集合修改时报错

            foreach (var tab in leftTabs)
            {
                CloseTab(tab);
            }
        }

        /// <summary>
        /// 关闭右侧Tab
        /// </summary>
        private void CloseRightTabs(TabItemModel tabItemModel)
        {
            if (OpenTabs?.Any() != true)
            {
                return;
            }

            int currentIndex = OpenTabs.IndexOf(tabItemModel);
            if (currentIndex < 0 || currentIndex >= OpenTabs.Count - 1)
            {
                return;
            }

            var rightTabs = OpenTabs
                .Skip(currentIndex + 1)
                .Where(t => t.IsClosable)
                .ToList();

            foreach (var tab in rightTabs)
            {
                CloseTab(tab);
            }
        }

        /// <summary>
        /// 关闭其他Tab（仅保留当前）
        /// </summary>
        private void CloseOtherTabs(TabItemModel tabItemModel)
        {
            if (OpenTabs?.Any() != true)
            {
                return;
            }

            var otherTabs = OpenTabs
                .Where(t => t != tabItemModel && t.IsClosable)
                .ToList();

            foreach (var tab in otherTabs)
            {
                CloseTab(tab);
            }
        }

        /// <summary>
        /// 关闭全部（包括当前）
        /// </summary>
        private void CloseAllTabs(TabItemModel tabItemModel)
        {
            if (OpenTabs?.Any() != true)
            {
                return;
            }

            var allClosableTabs = OpenTabs
                .Where(t => t.IsClosable)
                .ToList();

            foreach (var tab in allClosableTabs)
            {
                CloseTab(tab);
            }
        }
    }
}
